#include <STC15F2K60S2.H>
#include "Tim.h"
#include "Seg.h"
#include "Key.h"
#include "LED.h"
#include "stdio.h"
#include "Onewire.h"
#include "PWM.h"
//这个学习PWM使用，和温度读取，数码管，按键，灯
//各个对应在哪，就在哪实现，自己增加变量和逻辑
//sprintf(pucSeg_Buf,"        n");
sbit Pwm_Out=P3^4;
unsigned char ucPwm,ucPlus;
unsigned int uiTemp;
unsigned long ulms,ulKey_Time;
unsigned char pucSeg_Buf[9],pucSeg_Code[8],ucSeg_Pos;
unsigned int ucSeg_Dly;
unsigned char ucKey_Dly,ucKey_Old;
unsigned char ucState;
unsigned char ucSec;
unsigned char ucTemp_Flag;
unsigned char ucLed;
unsigned char ucSeg_Flag;
void Key_Proc(void) ;
void Seg_Proc(void);
void main(){
	Cls_Peripheral() ;
	Timer1Init();
	Timer0Init();
	while(1){
		Key_Proc();
		Seg_Proc();
}
}
void Time_1(void) interrupt 3 //定时器1中断函数
{ 
	 ulms++; 
	 if(!(ulms % 1000)) 
	 { 
		 if(ucSec) {
			 ucSec--;
			 if(!ucSec) {
				 ucLed=0;
				 ucSeg_Flag=0;
			 }
		 }
	} 
	 if(++ucSeg_Dly==500) ucSeg_Dly=0;
	 if(++ucKey_Dly==20) ucKey_Dly=0;
	 Seg_Disp(pucSeg_Code, ucSeg_Pos);
	if(++ucSeg_Pos==8) ucSeg_Pos=0;
}
void Key_Proc(void)  //按键功能在按键函数实现
{ 
	 unsigned char ucKey_Val, ucKey_Down, ucKey_Up; 
	 if(ucKey_Dly) return; 
		ucKey_Dly = 1; 
	 ucKey_Val = Key_Read(); 
	 ucKey_Down = ucKey_Val & (ucKey_Old ^ ucKey_Val); 
	 ucKey_Up = ~ucKey_Val & (ucKey_Old ^ ucKey_Val); 
	 ucKey_Old = ucKey_Val; 
	switch(ucKey_Down){
		case 4:
			if(++ucState==3) ucState=0;
			switch(ucState){
				case 0://有些可以直接在按键函数里实现，也可以写一个处理函数来实现
					ucPlus=2;
					ucLed|=0x01; 
					ucLed&=~6;
					break;
				case 1:
					ucPlus=5;
					ucLed|=0x02;
					ucLed&=~5;
					break;
				case 2:
					ucPlus=7;
					ucLed|=0x04;
					ucLed&=~3;
					break;
			}
			break;
		case 5:
			if(++ucSeg_Flag==3) ucSeg_Flag=0;
			switch(ucSeg_Flag){
				case 0:
					ucSec=0;
					break;
				case 1:
					ucSec=60;
					break;
				case 2:
					ucSec=120;
					break;
			}
			 break;
			//ucSec+=60;
//		   if(ucSec>=180) ucSec=0;
//			else if(ucSec>=120) ucSec=120;
//			else if(ucSec>=60) ucSec=60;
		   case 8:
				ucTemp_Flag^=1;
				break;
			case 9:
				ucSec=0;
				ucSeg_Flag=0;
				Pwm_Out=0;
				ucLed=0;
				break;
	}
}
void Seg_Proc(void){//数码管显示利用别的函数的变量来实现
	if(ucSeg_Dly) return;
	ucSeg_Dly=1;
	uiTemp=rd_temperature();
	if(ucTemp_Flag) {
		sprintf(pucSeg_Buf,"-4-  %02dC",uiTemp/16);
	}
	else{
		sprintf(pucSeg_Buf,"-%1d- %04d",(unsigned int)ucState+1,(unsigned int)ucSec);
	
	}
	Seg_Tran(pucSeg_Buf, pucSeg_Code);
}
void Time_0(void) interrupt 1{
	if(ucSec){//实现功能要看条件限制来增加语句
		if(++ucPwm==10) ucPwm=0;
		if(ucPlus){
			if(!ucPwm){
				Pwm_Out=1;
				ucLed|=0x80;
			}
			else if(ucPwm==ucPlus){
				Pwm_Out=0;
				ucLed&=0x7f;
			}
		}
	}
	else{
		ucLed&=0x7f;
	}
	Led_Disp(ucLed) ;
}